// 标签页分组管理组件
// 支持标签页分组、拖拽到分组、分组管理等功能

import React, { useState, useCallback } from 'react';
import { 
  Plus, 
  X, 
  Edit3, 
  Folder, 
  FolderOpen,
  MoreHorizontal,
  Users,
  Palette
} from 'lucide-react';
import { useTabStore, TabGroup } from '../stores/tabStore';
import { cn } from '../utils/cn';

// 分组颜色选项
const GROUP_COLORS = [
  { name: '蓝色', value: 'blue', class: 'bg-blue-500' },
  { name: '绿色', value: 'green', class: 'bg-green-500' },
  { name: '红色', value: 'red', class: 'bg-red-500' },
  { name: '黄色', value: 'yellow', class: 'bg-yellow-500' },
  { name: '紫色', value: 'purple', class: 'bg-purple-500' },
  { name: '粉色', value: 'pink', class: 'bg-pink-500' },
  { name: '青色', value: 'cyan', class: 'bg-cyan-500' },
  { name: '橙色', value: 'orange', class: 'bg-orange-500' },
];

// 分组项组件属性
interface GroupItemProps {
  group: TabGroup;
  tabCount: number;
  onActivate: (groupId: string) => void;
  onEdit: (groupId: string) => void;
  onDelete: (groupId: string) => void;
  onColorChange: (groupId: string, color: string) => void;
}

// 分组项组件
const GroupItem: React.FC<GroupItemProps> = ({
  group,
  tabCount,
  onActivate,
  onEdit,
  onDelete,
  onColorChange,
}) => {
  const [showColorPicker, setShowColorPicker] = useState(false);
  const [showMenu, setShowMenu] = useState(false);

  const groupColor = GROUP_COLORS.find(c => c.value === group.color) || GROUP_COLORS[0];

  return (
    <div className="relative">
      <div
        className={cn(
          'flex items-center px-3 py-2 rounded-lg cursor-pointer transition-all duration-200',
          'hover:bg-gray-100 dark:hover:bg-gray-700',
          group.isActive && 'bg-blue-50 dark:bg-blue-900/20 border border-blue-300 dark:border-blue-600'
        )}
        onClick={() => onActivate(group.id)}
      >
        {/* 分组颜色指示器 */}
        <div className={cn('w-3 h-3 rounded-full mr-2', groupColor.class)} />
        
        {/* 分组图标 */}
        {group.isActive ? (
          <FolderOpen size={16} className="mr-2 text-blue-500" />
        ) : (
          <Folder size={16} className="mr-2 text-gray-500" />
        )}
        
        {/* 分组名称 */}
        <span className="flex-1 text-sm font-medium truncate">
          {group.name}
        </span>
        
        {/* 标签页数量 */}
        <span className="text-xs text-gray-500 dark:text-gray-400 mr-2">
          {tabCount}
        </span>
        
        {/* 更多操作按钮 */}
        <button
          className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600 opacity-0 group-hover:opacity-100 transition-opacity"
          onClick={(e) => {
            e.stopPropagation();
            setShowMenu(!showMenu);
          }}
        >
          <MoreHorizontal size={14} />
        </button>
      </div>

      {/* 操作菜单 */}
      {showMenu && (
        <div className="absolute right-0 top-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1 z-50 min-w-32">
          <button
            className="w-full px-3 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center"
            onClick={() => {
              onEdit(group.id);
              setShowMenu(false);
            }}
          >
            <Edit3 size={14} className="mr-2" />
            重命名
          </button>
          
          <button
            className="w-full px-3 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center"
            onClick={() => {
              setShowColorPicker(true);
              setShowMenu(false);
            }}
          >
            <Palette size={14} className="mr-2" />
            更改颜色
          </button>
          
          <div className="h-px bg-gray-200 dark:bg-gray-700 my-1" />
          
          <button
            className="w-full px-3 py-2 text-left text-sm hover:bg-red-50 dark:hover:bg-red-900/20 text-red-600 dark:text-red-400 flex items-center"
            onClick={() => {
              onDelete(group.id);
              setShowMenu(false);
            }}
          >
            <X size={14} className="mr-2" />
            删除分组
          </button>
        </div>
      )}

      {/* 颜色选择器 */}
      {showColorPicker && (
        <div className="absolute right-0 top-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg p-3 z-50">
          <div className="grid grid-cols-4 gap-2">
            {GROUP_COLORS.map((color) => (
              <button
                key={color.value}
                className={cn(
                  'w-6 h-6 rounded-full border-2 border-transparent hover:border-gray-300 dark:hover:border-gray-600',
                  color.class,
                  group.color === color.value && 'border-gray-400 dark:border-gray-500'
                )}
                title={color.name}
                onClick={() => {
                  onColorChange(group.id, color.value);
                  setShowColorPicker(false);
                }}
              />
            ))}
          </div>
        </div>
      )}

      {/* 点击外部关闭菜单 */}
      {(showMenu || showColorPicker) && (
        <div
          className="fixed inset-0 z-40"
          onClick={() => {
            setShowMenu(false);
            setShowColorPicker(false);
          }}
        />
      )}
    </div>
  );
};

// 分组管理器组件属性
interface TabGroupManagerProps {
  className?: string;
  onGroupCreate?: (groupId: string) => void;
  onGroupDelete?: (groupId: string) => void;
}

// 标签页分组管理器组件
export const TabGroupManager: React.FC<TabGroupManagerProps> = ({
  className,
  onGroupCreate,
  onGroupDelete,
}) => {
  const {
    groups,
    activeGroupId,
    tabs,
    createGroup,
    deleteGroup,
    activateGroup,
    getTabsByGroup,
  } = useTabStore();

  const [showCreateForm, setShowCreateForm] = useState(false);
  const [newGroupName, setNewGroupName] = useState('');
  const [editingGroupId, setEditingGroupId] = useState<string | null>(null);
  const [editingGroupName, setEditingGroupName] = useState('');

  // 创建新分组
  const handleCreateGroup = useCallback(() => {
    if (newGroupName.trim()) {
      const groupId = createGroup(newGroupName.trim(), []);
      setNewGroupName('');
      setShowCreateForm(false);
      onGroupCreate?.(groupId);
    }
  }, [newGroupName, createGroup, onGroupCreate]);

  // 激活分组
  const handleActivateGroup = useCallback((groupId: string) => {
    activateGroup(groupId);
  }, [activateGroup]);

  // 编辑分组名称
  const handleEditGroup = useCallback((groupId: string) => {
    const group = groups.get(groupId);
    if (group) {
      setEditingGroupId(groupId);
      setEditingGroupName(group.name);
    }
  }, [groups]);

  // 保存分组名称
  const handleSaveGroupName = useCallback(() => {
    if (editingGroupId && editingGroupName.trim()) {
      // 这里应该调用更新分组名称的方法
      // updateGroupName(editingGroupId, editingGroupName.trim());
      setEditingGroupId(null);
      setEditingGroupName('');
    }
  }, [editingGroupId, editingGroupName]);

  // 删除分组
  const handleDeleteGroup = useCallback((groupId: string) => {
    const confirmed = window.confirm('确定要删除这个分组吗？分组中的标签页将被移到默认分组。');
    if (confirmed) {
      deleteGroup(groupId);
      onGroupDelete?.(groupId);
    }
  }, [deleteGroup, onGroupDelete]);

  // 更改分组颜色
  const handleColorChange = useCallback((groupId: string, color: string) => {
    // 这里应该调用更新分组颜色的方法
    // updateGroupColor(groupId, color);
  }, []);

  const groupList = Array.from(groups.values());

  return (
    <div className={cn('p-4 bg-gray-50 dark:bg-gray-900 border-r border-gray-200 dark:border-gray-700', className)}>
      {/* 标题 */}
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 flex items-center">
          <Users size={16} className="mr-2" />
          标签页分组
        </h3>
        
        <button
          className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700"
          onClick={() => setShowCreateForm(true)}
          title="创建新分组"
        >
          <Plus size={16} />
        </button>
      </div>

      {/* 创建分组表单 */}
      {showCreateForm && (
        <div className="mb-4 p-3 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
          <input
            type="text"
            placeholder="分组名称"
            value={newGroupName}
            onChange={(e) => setNewGroupName(e.target.value)}
            className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                handleCreateGroup();
              } else if (e.key === 'Escape') {
                setShowCreateForm(false);
                setNewGroupName('');
              }
            }}
            autoFocus
          />
          <div className="flex justify-end mt-2 space-x-2">
            <button
              className="px-2 py-1 text-xs text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"
              onClick={() => {
                setShowCreateForm(false);
                setNewGroupName('');
              }}
            >
              取消
            </button>
            <button
              className="px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600"
              onClick={handleCreateGroup}
              disabled={!newGroupName.trim()}
            >
              创建
            </button>
          </div>
        </div>
      )}

      {/* 分组列表 */}
      <div className="space-y-2">
        {groupList.map((group) => {
          const tabCount = getTabsByGroup(group.id).length;
          
          return (
            <div key={group.id} className="group">
              {editingGroupId === group.id ? (
                <div className="px-3 py-2">
                  <input
                    type="text"
                    value={editingGroupName}
                    onChange={(e) => setEditingGroupName(e.target.value)}
                    className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') {
                        handleSaveGroupName();
                      } else if (e.key === 'Escape') {
                        setEditingGroupId(null);
                        setEditingGroupName('');
                      }
                    }}
                    onBlur={handleSaveGroupName}
                    autoFocus
                  />
                </div>
              ) : (
                <GroupItem
                  group={group}
                  tabCount={tabCount}
                  onActivate={handleActivateGroup}
                  onEdit={handleEditGroup}
                  onDelete={handleDeleteGroup}
                  onColorChange={handleColorChange}
                />
              )}
            </div>
          );
        })}
      </div>

      {/* 空状态 */}
      {groupList.length === 0 && (
        <div className="text-center py-8">
          <Folder size={32} className="mx-auto text-gray-400 mb-2" />
          <p className="text-sm text-gray-500 dark:text-gray-400">
            还没有分组
          </p>
          <button
            className="mt-2 text-sm text-blue-500 hover:text-blue-600"
            onClick={() => setShowCreateForm(true)}
          >
            创建第一个分组
          </button>
        </div>
      )}
    </div>
  );
};
